<!DOCTYPE html>
<html class="Content">
<head>
    <title>xUnit.js: Creating Stubs</title>
    <link type="text/css" rel="Stylesheet" href="../../Style/documentation.css" />
</head>
<body>
    <h1>Creating Stubs</h1>
    <p>
        This example is based on <em>Examples/Source/Mocks and Stubs/Stubs.Dependencies.js</em> 
        and <em>Examples/Tests/Mocks and Stubs/StubTests.js</em> from <a href="examples.zip">examples.zip</a>.
    </p>
    <p>
        Often, code we are testing will consume complex objects, interfaces or hierarchies. These contracts can be fulfilled with lightweight structures called <strong>Stubs</strong>.
        xUnit.js provides a mechanism for quickly creating stubs with well-known shapes and outputs, as well as providing instrumentation recording invocations, arguments 
        and return values.
    </p>
    <h3>Source:</h3>
    <p>
        <span class="Code">
function openResults(targetWindow){
	var resultsWindow = targetWindow.open("results/url");
	return resultsWindow;
}
        </span>
    </p>
    <h3>Test:</h3>
    <p>
        <span class="Code">
Function.RegisterNamespace("Test");

[Import("../../Source/Mocks and Stubs/Stubs.Dependencies.js")]
[Fixture]
Test.StubTests=function(){
	[Fact]
	function ReturnsResultWindowHandle(){
		var expected="expected";
		var windowStub=Stubs.GetObject(
			{open:{returnValue:expected}}, 
			{location:"known/url"}
		);

		var actual=openResults(windowStub);
		
		Assert.Equal(expected, actual);
	}
}
        </span>
    </p>
    <p>
        Above, we can see that our <em>openResults()</em> method expects a <em>window</em> object with an <em>open()</em> method that returns a result.
    </p>
    <p>
        Since we don't have access to a true <em>window</em> object in our test, we can create a <strong>Stub</strong> with the required shape, and specify
        a known value as the result for our expectation.
    </p>
    <p>
        <strong>Stubs.GetObject(</strong><em>methods</em>,<em>properties</em><strong>)</strong> accepts two parameters, an object map of public methods to 
        create, and an object map of public properties to assign to the resulting stub.
    </p>
    <p>
        Methods can take the shape of a natural javascript method, i.e. {method:<em>function(parameter1, parameter2){return "returnValue";}</em>} - in which case the 
        method body will be executed - or the shape of an object map with an optional array of <em>parameters</em> and an optional <em>returnValue</em>,
        i.e. {method:<em>{parameters:["parameter1","parameter2"],returnValue:"returnValue"}</em>};
    </p>
</body>
</html>